package com.harmontronics.hanma.paas.paas.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.domain.app.entity.HmProcess;
import com.harmontronics.hanma.paas.paas.domain.app.entity.HmTask;
import com.harmontronics.hanma.paas.paas.domain.app.service.HmProcessHistoryService;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUser;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SubmitterUser;
import com.harmontronics.hanma.paas.paas.domain.organization.service.HmUserService;
import com.harmontronics.hanma.paas.paas.domain.organization.service.IHmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ldb
 */
@Service("hmProcessHistoryAppService")
@DS("#header.App-Unique")
public class HmProcessHistoryAppService extends HmProcessHistoryService {

    @Autowired
    private HmProcessRuntimeAppService hmProcessRuntimeAppService;

    @Autowired
    private IHmUserService hmUserService;

    @Override
    public PageBase<HmTask> listDown(Long processId, int pageNo, int pageSize) {
        PageBase<HmTask> pageBase =  super.listDown(processId, pageNo, pageSize);
        fillHmTaskPageBase(pageBase);
        return pageBase;
    }

    @Override
    public PageBase<HmTask> listTaskCC(Long processId, Boolean read, int pageNo, int pageSize){
        PageBase<HmTask> pageBase = super.listTaskCC(processId,read,pageNo,pageSize);
        fillHmTaskPageBase(pageBase);
        return pageBase;
    }

    public PageBase<HmTask> fillHmTaskPageBase(PageBase<HmTask> pageBase) {
        if (pageBase.isEmpty()) {
            return pageBase;
        }
        List<Long> submitterIds = pageBase.getData().stream().map(HmTask::getSubmitterId).map(Long::parseLong).collect(Collectors.toList());
        List<SubmitterUser> submitterUsers = hmUserService.selectSubmitterUserIn(submitterIds);
        for (HmTask hmTask : pageBase.getData()) {
            for (SubmitterUser submitterUser : submitterUsers) {
                if (hmTask.getSubmitterId().equals(submitterUser.getSubmitterId().toString())) {
                    hmTask.setSubmitterName(submitterUser.getSubmitterName());
                    hmTask.setSubmitterOrgId(submitterUser.getMainOrgId().toString());
                    hmTask.setSubmitterOrgName(submitterUser.getMainOrgName());
                }
            }
        }

        return pageBase;
    }

}
